<script setup lang='ts'>
import type { TableColumnsType, TablePaginationConfig } from 'ant-design-vue'

// 根据ID获取类别详情 GET /api/categories/detail/${param0}
const { data } = useRequest(() => apiCategoriesDetailReq({
  id: '1',
}))

const { data: dataList, current, pageSize, run, refresh } = usePagination(apiCategoriesListReq, {
  defaultParams: [{
    limit: 5,
  }],
  pagination: {
    currentKey: 'page',
    pageSizeKey: 'limit',
    totalKey: 'pagination.total',
  },
})

// 表单数据
const formState = reactive({
  name: '',
})

// 查询表单 目的是为了和表单数据脱邦
const searchForm = reactive({})

// 配置项
const columns = reactive<TableColumnsType<API.Category>>([
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '描述',
    customRender: ({ record }) => record.description ?? '--',
  },
  {
    title: '创建时间',
    dataIndex: 'createdAt',
  },
  {
    title: '操作',
    dataIndex: 'action',
  },
])

// 分页配置
const pagination = computed<TablePaginationConfig>(() => ({
  current: current.value,
  pageSize: pageSize.value,
  total: dataList.value?.pagination?.total,
  showTotal: total => `共${total}条`,
  onChange: (page: number, limit: number) => {
    // current.value = page
    // pageSize.value = size
    run({
      page,
      limit,
      ...searchForm,
    })
  },
}))

// 删除
const handleDel = (record: API.Category) => {
  // 删除类别 GET /api/categories/delete/${param0}
  apiCategoriesDeleteReq({
    id: record.id!,
  }).then(refresh)
}

// 查询
const handleSearch = () => {
  Object.assign(searchForm, formState)
  run({
    page: 1,
    limit: 5,
    ...searchForm,
  })
}
</script>

<template>
  <div>
    <h1>vue3如何发请求</h1>
    {{ data?.name }}
    <h3>分页</h3>
    <div mb20 w300 flex gap-20>
      <a-input v-model:value="formState.name" placeholder="请输入" />
      <a-button type="primary" @click="handleSearch">查询</a-button>
    </div>
    <a-table :data-source="dataList?.items" :columns="columns" :pagination="pagination">
      <template #bodyCell="{ record, column }">
        <template v-if="column.dataIndex === 'action'">
          <a-button ml--8 type="link" @click="handleDel(record as any)">删除</a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>

<style lang='less' scoped>

</style>
